package com.scalar.chiptrack.operations.shippingRequest;

import com.scalar.chiptrack.utils.ConfigManager;
import com.scalar.chiptrack.utils.StringUtils;
import com.scalar.chiptrack.utils.PDFGenerator;
import com.scalar.chiptrack.commons.Constants;
import com.scalar.chiptrack.commons.Address;
import com.scalar.ScalarException;

import java.io.FileWriter;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

/**
 * Created by ChandraSekhar.
 * User: Administrator
 * Date: Nov 21, 2005
 * Time: 3:11:35 PM
 */
public class ShippingRequestMailAck
{
    public static String getShipRequestPDFAck( ShippingRequest shippingRequest ) throws ScalarException
    {

        String fileXMLPath = null;
        String filePDFPath = null;

        String saAsXML = formatAsXML( shippingRequest );

        if ( saAsXML == null )
        {
            return fileXMLPath;
        }

        FileWriter fWriter = null;
        File saPDFAttachment = null;
        File saXML = null;

        try
        {
            // CREATE TEMPORARY ATTACHMENT FILE
            String mailingTempDir = ConfigManager.getMailerTempDir ();
            File tempDir = new File ( mailingTempDir ).getCanonicalFile ();
            tempDir.mkdir ();
            String xmlFileName = "Ship Request - "+shippingRequest.getShipReqNumber() + ".xml";
            String saAttachmentPDFFileName = "Ship Request - "+shippingRequest.getShipReqNumber();

            saAttachmentPDFFileName = saAttachmentPDFFileName + ".pdf";
            saAttachmentPDFFileName = StringUtils.convertLowerCaseToUpperCase( saAttachmentPDFFileName );

            String xsltFileName = ConfigManager.getShippingRequestXml2PdfXslFile ();

            saXML = new File ( tempDir.getCanonicalPath (), xmlFileName );
            saXML.deleteOnExit ();

            saPDFAttachment = new File ( tempDir.getCanonicalPath (), saAttachmentPDFFileName );
            saPDFAttachment.deleteOnExit ();

            if ( ( saXML.exists () == true ) || ( saXML.createNewFile () == true ) )
            {
                fWriter = new FileWriter ( saXML, false );
                fWriter.write ( saAsXML );
                fWriter.close ();
                fWriter = null;

                fileXMLPath = saXML.getCanonicalPath ().toUpperCase ();
                filePDFPath = saPDFAttachment.getCanonicalPath ().toUpperCase ();

                PDFGenerator.convertXML2PDF ( fileXMLPath, xsltFileName, filePDFPath );
            }
        }
        catch ( Exception e )
        {
            System.out.println ( "Exception while creating Ship Request Ack PDF file" );
            e.printStackTrace ();
        }
        finally
        {
            if ( fWriter != null )
            {
                try
                {
                    fWriter.close ();
                    fWriter = null;
                }
                catch ( IOException ignore )
                {
                }
            }
        }

        return filePDFPath;
    }

    public static String formatAsXML ( ShippingRequest shippingRequest ) throws ScalarException
    {
        StringBuffer buf = new StringBuffer ( 2098 );


        String imagesDirLocation 	= ConfigManager.getChipTracImagesDir();

        String crossCancel 			= ConfigManager.getCrossCanelImage();
        buf.append ( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "\n" );
        if ( Constants.RELEASE_STATUS_CANCELLED.equalsIgnoreCase ( shippingRequest.getStatus() ) )
        {
            buf.append ( "<shipRequestAcknowledgement cancel='1'> \n" );
            buf.append ( "<bgColor></bgColor> \n" );
        }
        else
        {
            buf.append ( "<shipRequestAcknowledgement cancel='0'> \n" );
            buf.append ( "<bgColor>#FFFFEE</bgColor> \n" );
        }
        buf.append ( "<images>\n" );
        buf.append ( "<cancelImage>"+imagesDirLocation+crossCancel+"</cancelImage> \n" );
        buf.append ( "</images>\n" );
        buf.append ( "<fromVendorName><![CDATA[" +( ( shippingRequest.getFromVendorName() != null ) ? shippingRequest.getFromVendorName() : "" ) + "]]></fromVendorName>" + "\n" );

        buf.append ( "<fromVendorAddress> \n" );
        try
        {
            buf.append( getXMLFormattedAddress( shippingRequest.getFromVendorAddress() ));
        }
        catch (Exception e)
        {
            buf.append ( "<address1/> \n" );
            buf.append ( "<address2/> \n" );
            buf.append ( "<address3/> \n" );
            buf.append ( "<phone/> \n" );
            buf.append ( "<fax/> \n" );
            System.out.println(" Exception in formatAsXML: " +e);
        }
        buf.append ( "</fromVendorAddress> \n" );

        buf.append ( "<toVendorName><![CDATA[" +( ( shippingRequest.getToVendorName() != null ) ? shippingRequest.getToVendorName() : "" ) + "]]></toVendorName>" + "\n" );

        buf.append ( "<toVendorAddress> \n" );
        try
        {
            buf.append( getXMLFormattedAddress( shippingRequest.getToVendorAddress() ));
        }
        catch (Exception e)
        {
            buf.append ( "<address1/> \n" );
            buf.append ( "<address2/> \n" );
            buf.append ( "<address3/> \n" );
            buf.append ( "<phone/> \n" );
            buf.append ( "<fax/> \n" );
            System.out.println(" Exception in formatAsXML: " +e);
        }
        buf.append ( "</toVendorAddress> \n" );
        buf.append ( "<shipReqNumber><![CDATA[" +( ( shippingRequest.getShipReqNumber() != null ) ? shippingRequest.getShipReqNumber() : "" ) + "]]></shipReqNumber>" + "\n" );
        buf.append ( "<shipReqDate><![CDATA[" +( ( shippingRequest.getShipReqDate() != null ) ? shippingRequest.getShipReqDate() : "" ) + "]]></shipReqDate>" + "\n" );
        buf.append ( "<shipperName><![CDATA[" +( ( shippingRequest.getShipperName() != null ) ? shippingRequest.getShipperName() : "" ) + "]]></shipperName>" + "\n" );
        buf.append ( "<shipAlerts><![CDATA[" +( ( shippingRequest.getShipAlerts() != null ) ? shippingRequest.getShipAlerts() : "" ) + "]]></shipAlerts>" + "\n" );
        buf.append ( "<partNumber><![CDATA[" +( ( shippingRequest.getPartNumber() != null ) ? shippingRequest.getPartNumber() : "" ) + "]]></partNumber>" + "\n" );
        buf.append ( "<totalQty><![CDATA[" +( shippingRequest.getTotalQty() ) + "]]></totalQty>" + "\n" );

        ArrayList lotList = shippingRequest.getLotList();

        buf.append ( "<lotDetails>" + "\n" );
        for( int i=0; i<lotList.size(); i++ )
        {
            ShippingRequestLot shippingRequestLot = (ShippingRequestLot) lotList.get(i);
            buf.append ( "<lotData>" + "\n" );
            buf.append ( "<lotNumber><![CDATA[" + ( ( shippingRequestLot.getLotNumber() != null ) ? shippingRequestLot.getLotNumber() : "" ) + "]]></lotNumber>" + "\n" );
            buf.append ( "<qtyPulled><![CDATA[" + ( shippingRequestLot.getPulledQty() ) + "]]></qtyPulled>" + "\n" );
            buf.append ( "</lotData>" + "\n" );
        }

        buf.append ( "</lotDetails>" + "\n" );

        buf.append ( "<specialInstrs><![CDATA[" +( ( shippingRequest.getSpecialInstr() != null ) ? shippingRequest.getSpecialInstr() : "" ) + "]]></specialInstrs>" + "\n" );

        buf.append ( "</shipRequestAcknowledgement>" + "\n" );
        return buf.toString();
    }

    public static String getFormatedState( Address add )
    {
        String addr = "";
        if (  add.getState() != null  &&  add.getState().trim().length() != 0 )
            addr =  add.getState();
        if( add.getZipCode() != null &&  add.getZipCode().trim().length() != 0 )
        {
             if ( addr.trim().length() !=0 )
                 addr = addr + "&nbsp;-&nbsp;" + add.getZipCode();
            else
                 addr = addr + add.getZipCode();
        }
        if( add.getCountry() != null && add.getCountry().trim().length() != 0 )
        {
            if ( addr.trim().length() != 0 )
                addr = addr + ",&nbsp;" + add.getCountry();
            else
                addr = addr + add.getCountry();
           }

        return addr;
    }


    public static String getXMLFormattedAddress( Address add )
    {
        StringBuffer formatAddress = new StringBuffer();
        formatAddress.append( "<contactPerson><![CDATA[" );
        formatAddress.append ( ( ( add.getContactPerson() != null ) && ( ( add.getContactPerson().trim().length() > 0 ) ) ) ? add.getContactPerson() : "" );
        formatAddress.append( "]]></contactPerson>" );

        formatAddress.append( "<address1><![CDATA[" );
        formatAddress.append ( ( ( add.getAddress1() != null ) && ( ( add.getAddress1().trim().length() > 0 ) ) ) ? add.getAddress1() : "" );

          formatAddress.append ( "]]></address1> \n" );
        formatAddress.append( "<address2><![CDATA[" );
        formatAddress.append ( ( ( add.getAddress2() != null ) && ( ( add.getAddress2().trim().length() > 0 ) ) ) ? add.getAddress2() : "" );

        formatAddress.append ( "]]></address2> \n" );
        formatAddress.append( "<address3><![CDATA[" );
        formatAddress.append ( ( ( add.getAddress3() != null ) && ( ( add.getAddress3().trim().length() > 0 ) ) ) ? add.getAddress3() : "" );
        formatAddress.append ( "]]></address3> \n" );
        formatAddress.append( "<address4><![CDATA[" );
        formatAddress.append ( ( ( add.getAddress4() != null ) && ( ( add.getAddress4().trim().length() > 0 ) ) ) ? add.getAddress4() : "" );
        formatAddress.append ( "]]></address4> \n" );
        formatAddress.append( "<city><![CDATA[" );
        formatAddress.append ( ( ( add.getCity() != null ) && ( add.getCity().trim().length() > 0 ) ) ? add.getCity()  : "" );
        formatAddress.append ( "]]></city> \n" );

        String formatedState = "";
        formatedState = getFormatedStateXPDL(add);
        if ( formatedState.trim().length() > 0 )
            formatAddress.append( "<state><![CDATA["+formatedState+"]]></state> \n" );

        formatAddress.append ( "<phone><![CDATA[" );
        formatAddress.append ( ( ( add.getPhoneNumber() != null ) && ( add.getPhoneNumber().trim().length() > 0 ) ) ?  "Tel: "+ add.getPhoneNumber()+"" : "");//modified by varma 06 jul 2004
        formatAddress.append ( "]]></phone> \n" );

        formatAddress.append ( "<fax><![CDATA[" );
        formatAddress.append ( ( ( add.getFaxNumber() != null ) && ( add.getFaxNumber().trim().length() > 0 ) ) ?  "Fax: "+ add.getFaxNumber() : "" );
        formatAddress.append ( "]]></fax> \n" );
        formatAddress.append ( "<cellno><![CDATA[" );
        formatAddress.append ( ( ( add.getCellNumber() != null ) && ( add.getCellNumber().trim().length() > 0 ) ) ?  "Cell No: "+ add.getCellNumber() : "");
        formatAddress.append ( "]]></cellno> \n" );
        formatAddress.append ( "<email><![CDATA[" );
        formatAddress.append ( ( ( add.getEmail() != null ) && ( add.getEmail().trim().length() > 0 ) ) ?  "Email: "+ add.getEmail() : "" );
        formatAddress.append ( "]]></email> \n" );

        return formatAddress.toString() ;
    }
    public static String getFormatedStateXPDL ( Address add )
	{
		String addr = getFormatedState(add);
		String  temp = addr.replaceAll("&nbsp;"," ");
		return temp;
	}


}
